/********************************************************
* pvp.js:
* Contains all code related to player vs player ttt games
*
*********************************************************/

var myPiece = "";	//This player's piece
var prevBoard = "NNNNNNNNN";	//Keeps track of prev board, used to know turn change
var isTurn = false;	//Start off as not my turn
var timerStarted = false;	//Timer is not started by default
var t;	//Timer variable t
var c = 0;	//I'm not sure what this is and I'm afraid to delete it.


/* Perodically (every second) sends a request to the server with the current board */
function periodicCheck(){
	if(!isTurn)	//Only in "sending state" when it's not our turn.
		txBoard();	//Transmits the board (or other info) to servlet
	t = setTimeout("periodicCheck()", 1000);	//Recursive call
}

/* Safety function for timer. periodicCheck is called NO WHERE ELSE but here. */
function startTimer(){
	if(!timerStarted){	//Don't want duplicate timers. BAD THINGS HAPPEN.
		timerStarted = true;
		periodicCheck()
	}
}

/* What happens when back is pressed in pvpinfo.htm. Reset ALL THE THINGS */
function pvp_backPressed(){
	clearTimeout(t);	//Ensure timer is stopped.
	resetFiles();	//Reset the pvp file (request to server)
	isTurn = false;	//Not my turn now.
	timerStarted = false;	//Timer is no longer running.
	prevBoard = "NNNNNNNNN"	//Reset the last board
	setBoard("NNNNNNNNN");	//Reset the current board
	resetDivBG();	//Reset the backgrounds (if set)
	replacePage('opponent.htm', 'side');	//Return to menu
}

/* XMLHttpRequest to servlet */
/*Occurs when "player" button is pressed. */
function initPvP(){
	replacePage('pvpInfo.htm', 'side');	//Show pvp info
	setBoard("NNNNNNNNN");	//Reset the board yadd yada
	resetDivBG();
	setCookie("wins", 0);
	setCookie("losses", 0);
		
	var req = new XMLHttpRequest();	//Create request

	//Checks whether this player should be X or O based on response
	//TRUE is X, FALSE is O
	req.open("get", "servlet/pvp_move/checkx", true);
	req.onreadystatechange = function(){
		if ( req.readyState == 4) {
	    	var d = req.responseXML.documentElement; //Get XML response
			var resps = d.textContent	//Response string in form of [true/false] 
			if(resps == "true"){	//Set player piece (and display image) accordingly
				myPiece = "X";
				document.getElementById('playerPiece').src = "imgs/x_btn.png";
			}else{
				myPiece = "O";
				document.getElementById('playerPiece').src = "imgs/o_btn.png";
			}
			startTimer();	//Start the timer for checking updates
			if(myPiece == "X")	//X Goes first. CLASSIC RULES.
				isTurn = true;
			else
				isTurn = false;
		}	
	}
    req.send( null );
}

/* Sends all non-checkx requests to servlet */
function txBoard(){
	var req = new XMLHttpRequest();
	var reqText;

	if(!isTurn)	//We're in listening (ie receiving) state when it's NOT our turn
		reqText = "listening";	//Server knows to listen for this
	else	//Else we give them the new board
		reqText = getBoard();	//This is the new board
	
	req.open("get", "servlet/pvp_move/"+reqText, true);
	req.onreadystatechange = function(){
		if ( req.readyState == 4) {
			rxResponse(req);	//Deal with the response
		}
	}

	req.send(null);
}

/* Receives response in form of [board];[state] */
function rxResponse(req){
	var d = req.responseXML.documentElement; //Get XML response
	var r = d.textContent.split(';');	//board and state separated by a ;
	var rBoard = r[0]; //Board from response
	var rState = r[1]; //State from response
	
	compareBoard(rBoard); //Compares this board with prev
	pvp_checkState(rState);	//Updates state
}

/* Compares a board with the previous one */
function compareBoard(b){	//Different boards mean the OTHER player placed a piece
	if(b != prevBoard && b != "xIsNotTaken"){	//Latter is weird bug. Hack to deal.
		setBoard(b);	//Set to new board
		isTurn = true;	//It's now our turn.
		setStatus("Your move.");	//Inform the user to do something
	}
}

/* A little different from AI check state. */
function pvp_checkState(state){
	if(state == "IN_PROGRESS"){
	//Don't really need to do anything
	}else{
		if(state == "X_WON"){
			pvp_onWin("X");
		}else if(state == "O_WON"){
			pvp_onWin("O");
		}else if(state == "DRAW"){
			pvp_onWin("D"); //Draw
		}
	} 
}

/* I'm tired of explaining self-explanatory stuff. My code is very readable. */
function pvp_onWin(p){
	//alert(p + " won");
	if(p == myPiece){
		setStatus("You Win! Press 'back'.");
		setCookie("wins", parseInt(getCookie("wins"))+1);
	}else if(p == "D"){
		setStatus("Draw.");
	}else{
		setStatus("Opponent Wins. Press 'back'.");
		setCookie("losses", parseInt(getCookie("losses"))+1);
	}
	highlightWin(p);
	updateScores();
	clearTimeout(t);	//Game ended stop the timer
	
	//Unlike AI, we do no fancy piece swap. We simply ran out of time and
	//our ambitions were a little high. This is pretty decent if you ask me.
	//It wouldn't be too difficult to do, but I'm out of patience. KTHXBAI.
}

//Set piece, call some stuf
function pvp_setXO(row, col){
	if(isTurn){	//User can only click if it's their turn
		var sqr = document.getElementById(row+","+col); //Get the div clicked
		if(sqr.innerHTML == ""){	//Make sure it's blank
			sqr.innerHTML = myPiece;	//Set the piece
			txBoard() //Sends the new board once (way around timer)
			isTurn = false;
			setStatus("Waiting for other player.");
			prevBoard = getBoard();
			//periodicCheck(); //Starts listening
		}
	}else{
		alert("Not your turn.");
	}
}
